<template>
	<cl-dialog title="开班" v-model="visible" width="90%">
		<div class="select-row">
			<div class="select-item">
				<cl-label>选择门店</cl-label>
				<cl-select v-model="currentShopId" :options="dict.get('Shop')" prop="status" />
			</div>
			<div class="select-item">
				<cl-label>选择医生</cl-label>
				<cl-select
					v-model="currentDoctorId"
					:options="doctorList"
					prop="status"
					placeholder="请先选择门店"
				/>
			</div>
		</div>
		<div class="select-item">
			<div class="input-group">
				<div class="input-field">
					<cl-label>日期选择</cl-label>
					<cl-date-picker
						v-model="startDate"
						type="valueFormat"
						prop="status"
						valueFormat="'YYYY-MM-DD'"
						placeholder="选择开始日期"
						style="width: 350px"
					/>
				</div>
			</div>
		</div>
		<div class="appointment-table" v-if="currentShopId && currentDoctorId">
			<table>
				<thead>
					<tr>
						<th>时间</th>
						<th v-for="(date, index) in weekDates" :key="index">
							{{ getWeekDayText(date.weekDay) }}({{ date.dateStr }})
						</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="time in timeSlots" :key="time.value">
						<td class="time-column">{{ time.label }}</td>
						<td
							v-for="(day, index) in 7"
							:key="index"
							class="time-slot"
							:class="{
								available: time.availableSlots[index],
								unavailable: !time.availableSlots[index],
								selected: selectedTime === time.value && selectedDay === index,
								'class-clickable':
									time.classId && time.classStyles && time.classStyles[index], // 修改这里，确保只有有班级样式的时间槽才可点击
								...(time.classStyles && time.classStyles[index]
									? { [time.classStyles[index]]: true }
									: {})
							}"
							:data-time="time.value"
							:data-weekday="weekDates[index].weekDay"
							@click="
								time.classId && time.classStyles && time.classStyles[index]
									? handleClassSelect(time.classId)
									: handleTimeSelect(time, index)
							"
						>
							<span v-if="time.appointments && time.appointments[index]">
								{{ time.appointments[index] }}
							</span>
						</td>
					</tr>
				</tbody>
			</table>
		</div>
		<div v-else>
			<div style="padding: 10px; text-align: center">请先选择医生和门店</div>
		</div>
		<div class="select-item" v-if="startDateTime != ''">
			<div class="input-group">
				<div class="input-field">
					<cl-label>上课时间</cl-label>
					<el-input
						v-model="startDateTime"
						type="text"
						placeholder="请输入开始时间"
						disabled
					/>
				</div>
				<div class="input-field">
					<cl-label>班级时长</cl-label>
					<el-input v-model="classLong" disabled type="text" />
				</div>
				<div class="input-field">
					<cl-label>班级名称</cl-label>
					<el-input v-model="className" type="text" />
				</div>
				<div class="input-field">
					<cl-label>班级人数</cl-label>
					<el-input v-model="classCount" type="number" />
				</div>
			</div>
		</div>
		<template #footer>
			<el-button
				type="primary"
				@click="handleConfirmAppointment"
				:disabled="!selectedTime || !currentShopId || !currentDoctorId"
			>
				确认开班
			</el-button>
		</template>
	</cl-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { useDict } from '/$/dict';
import { useCool } from '/@/cool';
import { ElMessage, ElMessageBox } from 'element-plus';

const { service } = useCool();
const { dict } = useDict();

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false
	},
	studentId: {
		type: Number,
		default: 0
	}
});

const emit = defineEmits(['update:modelValue', 'success']);

const visible = ref(false);
const currentDoctorId = ref('');
const currentShopId = ref('');
const selectedTime = ref('');
const startDate = ref(new Date().toISOString().split('T')[0]);
const doctorList = ref([]);
const timeSlots = ref([]);
const selectedDay = ref(-1);
const weekDates = ref([]);
const startDateTime = ref('');
const classLong = ref('60分钟');
const classCount = ref('5');
const className = ref('视训班级');

// 监听 modelValue 变化
watch(
	() => props.modelValue,
	val => {
		visible.value = val;
	}
);

// 监听 visible 变化
watch(
	() => visible.value,
	val => {
		emit('update:modelValue', val);
		if (!val) {
			resetForm();
		}
	}
);

// 监听选择变化
watch([currentDoctorId, currentShopId, startDate], ([newDoctorId, newShopId, newStartDate]) => {
	if (newShopId) {
		getDoctorList(newShopId);
	}
	if (newDoctorId && newShopId && newStartDate) {
		calculateWeekDates(newStartDate);
		getAppointmentList();
	}
});

// 计算一周的日期
function calculateWeekDates(startDateStr: string) {
	const dates = [];
	const start = new Date(startDateStr);

	for (let i = 0; i < 7; i++) {
		const date = new Date(start);
		date.setDate(date.getDate() + i);
		dates.push({
			weekDay: date.getDay(),
			dateStr: `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
		});
	}

	weekDates.value = dates;
}

// 获取星期几的文字
function getWeekDayText(day: number): string {
	const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	return weekDays[day];
}

// 获取医生列表
async function getDoctorList(shopId: number) {
	const res = await service.doctor.info.getSelectlist({ shopId: shopId });
	if (res) {
		doctorList.value = res;
	}
}

function generateTimeSlots(startTime: string, endTime: string) {
	const slots = [];
	const start = new Date(`2000/01/01 ${startTime}`);
	const end = new Date(`2000/01/01 ${endTime}`);

	while (start <= end) {
		const hours = start.getHours().toString().padStart(2, '0');
		const minutes = start.getMinutes().toString().padStart(2, '0');
		const timeStr = `${hours}:${minutes}`;

		const availableSlots = new Array(7).fill(true);
		// 处理工作日的9:00和9:30不可预约
		if (timeStr === '09:00' || timeStr === '09:30') {
			// 根据weekDates中的weekDay判断是否为工作日
			weekDates.value.forEach((date, index) => {
				// weekDay为1-5表示周一到周五
				if (date.weekDay >= 1 && date.weekDay <= 5) {
					availableSlots[index] = false;
				}
			});
		}

		slots.push({
			label: timeStr,
			value: timeStr,
			availableSlots: availableSlots,
			appointments: new Array(7).fill(null)
		});

		start.setMinutes(start.getMinutes() + 30);
	}
	return slots;
}

async function getAppointmentList() {
	const startDateStr = new Date(startDate.value).toISOString().split('T')[0];
	const endDate = new Date(startDate.value);
	endDate.setDate(endDate.getDate() + 7);
	const endDateStr = endDate.toISOString().split('T')[0];

	const params = {
		date: startDateStr,
		endDate: endDateStr,
		shopId: currentShopId.value,
		doctorId: currentDoctorId.value
	};

	try {
		// const resAppoint = await service.appointment.info.dateAppoint(params);
		const resAppoint = false;
		const resClass = await service.appointment.info.dateClass(params);
		// 初始化时间槽
		timeSlots.value = generateTimeSlots('09:00', '19:30');
		if (resAppoint) {
			// 处理已预约时间
			resAppoint.forEach(appointment => {
				const appointmentDateTime = new Date(appointment.appointmentTime);
				const timeStr = `${appointmentDateTime.getHours().toString().padStart(2, '0')}:${appointmentDateTime.getMinutes().toString().padStart(2, '0')}`;

				// 计算日期是否在当前周内
				const appointmentDate = appointmentDateTime.toISOString().split('T')[0];
				const dayIndex = weekDates.value.findIndex(date => {
					const appointmentMonth = appointmentDate.substring(5, 7);
					const appointmentDay = appointmentDate.substring(8, 10);
					return date.dateStr === `${appointmentMonth}-${appointmentDay}`;
				});

				// 找到对应的时间槽并标记为不可用
				const timeSlot = timeSlots.value.find(slot => slot.value === timeStr);
				if (timeSlot && dayIndex !== -1) {
					let displayName = appointment.userName || '未知预约人';
					if (!props.isPage && displayName !== '未知预约人') {
						if (displayName.length === 2) {
							displayName = displayName.charAt(0) + '*';
						} else if (displayName.length > 2) {
							displayName = displayName.charAt(0) + '*' + displayName.substring(2);
						}
					}
					// timeSlot.availableSlots[dayIndex] = false;
					timeSlot.appointments[dayIndex] = displayName;
					timeSlot.availableSlots[dayIndex] = false;
				}
			});
		}
		// 处理课程占位，不依赖于 resAppoint 的存在
		if (resClass) {
			resClass.forEach(classItem => {
				const startDateTime = new Date(classItem.startTime);
				const endDateTime = new Date(classItem.endTime);

				// 获取开始和结束时间的小时和分钟
				const startHour = startDateTime.getHours();
				const startMinute = startDateTime.getMinutes();
				const endHour = endDateTime.getHours();
				const endMinute = endDateTime.getMinutes();

				// 计算日期在当前周的哪一天
				const classDate = startDateTime.toISOString().split('T')[0];
				const dayIndex = weekDates.value.findIndex(date => {
					const classMonth = classDate.substring(5, 7);
					const classDay = classDate.substring(8, 10);
					return date.dateStr === `${classMonth}-${classDay}`;
				});

				if (dayIndex !== -1) {
					let isFirstSlot = true;
					let slotCount = 0;
					// 计算总时间槽数
					const totalSlots = Math.ceil(
						(endDateTime.getTime() - startDateTime.getTime()) / (30 * 60 * 1000)
					);

					// 遍历时间段，标记课程占用的时间槽
					timeSlots.value.forEach(slot => {
						const [slotHour, slotMinute] = slot.value.split(':').map(Number);
						const slotTime = slotHour * 60 + slotMinute;
						const startTime = startHour * 60 + startMinute;
						const endTime = endHour * 60 + endMinute;

						if (slotTime >= startTime && slotTime < endTime) {
							// 判断班级是否可以预约（人数未满）
							const isClassAvailable = classItem.currentCount < classItem.limitCount;
							slot.availableSlots[dayIndex] = isClassAvailable;
							if (!slot.classStyles) slot.classStyles = {};
							slot.classId = classItem.id; // 添加课程ID

							if (isFirstSlot) {
								// 修改这里，添加人数显示
								slot.appointments[dayIndex] =
									`${classItem.className}(${classItem.currentCount}/${classItem.limitCount})`;
								slot.classStyles[dayIndex] =
									`class-block first ${isClassAvailable ? 'available' : 'unavailable'}`;
								isFirstSlot = false;
							} else if (slotCount < totalSlots - 1) {
								slot.appointments[dayIndex] = '';
								slot.classStyles[dayIndex] =
									`class-block middle ${isClassAvailable ? 'available' : 'unavailable'}`;
							} else {
								slot.appointments[dayIndex] = '';
								slot.classStyles[dayIndex] =
									`class-block last ${isClassAvailable ? 'available' : 'unavailable'}`;
							}
							slotCount++;
						}
					});
				}
			});
		}
	} catch (error) {
		console.log('获取预约信息失败', error);
		ElMessage.error('获取预约信息失败');
	}
}

// 修改时间选择处理函数
function handleTimeSelect(time, dayIndex) {
	if (time.availableSlots[dayIndex]) {
		if (selectedTime.value === time.value && selectedDay.value === dayIndex) {
			selectedTime.value = '';
			selectedDay.value = -1;
			startDateTime.value = ''; // 重置开始时间显示
		} else {
			selectedTime.value = time.value;
			selectedDay.value = dayIndex;

			// 获取选中日期的年月日
			const selectedDateInfo = weekDates.value[dayIndex];
			const [month, day] = selectedDateInfo.dateStr.split('-');
			const currentYear = new Date().getFullYear();
			const dateStr = `${currentYear}-${month}-${day}`;

			// 拼接日期和时间
			startDateTime.value = `${dateStr} ${time.value}`; // 更新开始时间显示
		}
	}
}

// 修改预约确认函数
async function handleConfirmAppointment() {
	if (!selectedTime.value || selectedDay.value === -1) {
		ElMessage.warning('请选择预约时间');
		return;
	}

	// 使用选中日期对应的完整日期
	const selectedDateInfo = weekDates.value[selectedDay.value];
	if (!selectedDateInfo) {
		ElMessage.warning('日期选择有误');
		return;
	}

	// 计算结束时间（一小时后）
	const startDate = new Date(startDateTime.value);
	const endDate = new Date(startDate.getTime() + 60 * 60 * 1000); // 加一小时
	const endTime = `${endDate.getFullYear()}-${String(endDate.getMonth() + 1).padStart(2, '0')}-${String(endDate.getDate()).padStart(2, '0')} ${String(endDate.getHours()).padStart(2, '0')}:${String(endDate.getMinutes()).padStart(2, '0')}`;

	const params = {
		shopId: currentShopId.value,
		doctorId: currentDoctorId.value,
		startTime: startDateTime.value,
		endTime: endTime,
		limitCount: classCount.value,
		className: className.value,
		status: 1
	};

	try {
		await service.class.class.add(params);
		ElMessage.success('开班成功');
		visible.value = false;
		emit('success');
	} catch (error: any) {
		ElMessage.error(error.message || '开班失败');
	}
}

// 添加班级预约处理函数
async function handleClassSelect(classId: number) {
	return true;
}

// 重置表单
function resetForm() {
	// 重置所有状态
	currentDoctorId.value = '';
	currentShopId.value = '';
	selectedTime.value = '';
	startDate.value = new Date().toISOString().split('T')[0];
	doctorList.value = [];
	timeSlots.value = [];
	selectedDay.value = -1;
	weekDates.value = [];
	startDateTime.value = '';
	classLong.value = '60分钟';
	classCount.value = '5';
	className.value = '视训班级';
}
</script>

<style scoped>
.input-group {
	display: flex;
	gap: 20px;
	width: 100%;
}

.input-field {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.input-field :deep(.el-input),
.input-field :deep(.cl-date-picker) {
	width: 100%;
}
.select-row {
	display: flex;
	gap: 20px;
	margin-bottom: 20px;
}

.select-item {
	flex: 1;
}
.appoint-item {
	margin-top: 5px;
	margin-bottom: 20px;
}

.time-slot {
	text-align: center;
	cursor: pointer;
	transition: all 0.3s;
}

.time-slot.available {
	background-color: #e1f3d8;
	color: #67c23a;
}

.time-slot.unavailable {
	background-color: #fde2e2;
	color: #f56c6c;
	cursor: not-allowed;
}

/* 工作日早上时间段的特殊样式 */
td[data-weekday='1'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='2'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='3'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='4'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='5'].time-slot.unavailable[data-time='09:00'],
td[data-weekday='1'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='2'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='3'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='4'].time-slot.unavailable[data-time='09:30'],
td[data-weekday='5'].time-slot.unavailable[data-time='09:30'] {
	background-color: #f5f7fa !important;
	color: #909399 !important;
}

.time-slot.selected {
	background-color: #fff;
	border: 2px solid #409eff;
	color: #409eff;
}

.appointment-table {
	margin-top: 20px;
	overflow-x: auto;
	margin-bottom: 20px;
}

table {
	width: 100%;
	table-layout: fixed;
	border-collapse: collapse;
	border: 1px solid #dcdfe6;
}

th,
td {
	border: 1px solid #dcdfe6;
	padding: 3px;
	text-align: center;
	width: 12.5%;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.time-column {
	background-color: #f5f7fa;
	font-weight: bold;
	width: 12.5%;
}

/* 课程占位样式 */
.time-slot.class-block {
	position: relative;
	background-color: #fde2e2;
	color: #f56c6c;
	cursor: not-allowed;
	border: 1px solid #dcdfe6;
}

.time-slot.class-block.available {
	background-color: #fff7e6;
	color: #e6a23c;
	cursor: pointer;
}

.time-slot.class-block.first {
	border-bottom: none;
	border-radius: 4px 4px 0 0;
}

.time-slot.class-block.middle {
	border-top: none;
	border-bottom: none;
	color: transparent;
}

.time-slot.class-block.last {
	border-top: none;
	border-radius: 0 0 4px 4px;
}

.time-slot.class-clickable {
	cursor: pointer !important;
}

.time-slot.class-block .class-name {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	z-index: 1;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	width: 90%;
}

/* 页面模式样式 */
.appointment-page {
	padding: 20px;
	background: #fff;
	min-height: 100vh;
	display: flex;
	flex-direction: column;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
}

.page-content {
	max-width: 1200px;
	margin: 0 auto;
	flex: 1;
	overflow-y: auto;
	padding-bottom: 60px;
}

.info-display {
	margin-bottom: 20px;
	padding: 15px;
	background-color: #f5f7fa;
	border-radius: 4px;
}

.info-item {
	margin-bottom: 10px;
	display: flex;
	align-items: center;
}

.info-item:last-child {
	margin-bottom: 0;
}

.info-item .label {
	font-weight: bold;
	margin-right: 10px;
	min-width: 60px;
}

.info-item .value {
	color: #606266;
}
</style>
